<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList"></TodoHeader>

    <!-- 主体部分 -->
    <TodoBody
      :list="randerList"
      @changeStatus="changeStatus"
      @delList="delList"
      :isAll='isAll'
      @changeAll='changeAll'
    ></TodoBody>

    <!-- 底部部分 -->
    <TodoFooter
      :titleList="titleList"
      @clearList="clearList"
      :clearShow="clearShow"
      :type="type"
      @changeType="changeType"
      v-show="list.length"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue';
import TodoBody from '@/components/TodoBody.vue';
import TodoFooter from '@/components/TodoFooter.vue';
export default {
  components: {
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
  data() {
    return {
      type: 'all',
      list:JSON.parse(localStorage.getItem('list')) || [
        { id: 1, name: '吃饭', isDone: true },
        { id: 2, name: '睡觉', isDone: false },
        { id: 3, name: '打豆豆', isDone: true },
      ],
    };
  },
  methods: {
    //1.修改单选框状态
    changeStatus(id) {
      const str = this.list.find((item) => item.id === id);
      str.isDone = !str.isDone;
    },
    //2.删除
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    //3.添加
    addList(msg) {
      //id最好用当前的时间戳 唯一的
      const obj = { id: +new Date(), name: msg, isDone: false };
      this.list = [obj, ...this.list];
    },
    //5.清除已完成
    clearList() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    //7.改type
    changeType(type) {
      this.type = type;
    },
    //9.1.全选反选
    changeAll(flag){
       this.list.forEach(item =>item.isDone = flag)
    }
  },
  computed: {
    //4.剩余
    titleList() {
      return this.list.filter((item) => !item.isDone).length;
    },
    //6.只要有一个true就显示清除已完成按钮
    clearShow() {
      return this.list.some((item) => item.isDone);
    },
    //8.改完type显示新的数据
    randerList() {
      if (this.type === 'all') {
        return this.list;
      } else if (this.type === 'active') {
        return this.list.filter((item) => !item.isDone);
      } else if (this.type === 'completed') {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
   //9.2.全选反选
    isAll(){
      return this.list.every(item => item.isDone)

    }
  },
  watch: {
    list: {
      deep: true,
      immediate:true,
      handler(value) {
        localStorage.setItem('list', JSON.stringify(value));
      },
    },
  },
};
</script>

<style></style>
